<template>
  <Modal v-model:visible="visible" destroyOnClose :footer="null" :afterClose="afterClose" :width="1000">
    <template #title>
      <div class="equipDebugBox">
        <div class="title">
          设备调试
        </div>
        <a-switch v-model:checked="equipDebug" :loading="equipDebugSwitch" @click="equipDebugClick" />
      </div>
    </template>
    <div class="equipModalBox">
      <div class="headBox">
        <div class="headTitleBox">
          <div class="title1">
            <div :class="deviceType == 3 ? 'TabsBox borBot' : 'TabsBox'" @click="switchEquip(3)">
              <div class="img">
                <Image :preview="false" :src="deviceType == 3 ? airport_icon1 : airport_icon0"></Image>
              </div>
              <div :class="deviceType == 3 ? 'text1' : 'text'">机场</div>
            </div>
            <div :class="deviceType == 0 ? 'TabsBox borBot' : 'TabsBox'" @click="switchEquip(0)">
              <div class="img">
                <Image :preview="false" :src="deviceType == 0 ? drone_icon1 : drone_icon0"></Image>
              </div>
              <div :class="deviceType == 0 ? 'text1' : 'text'">无人机</div>
            </div>
          </div>
          <div class="title2">
            <a-badge v-show="deviceType == 3" :color="panelStatus?.state == '5' ? '#ff4d4f' : '#00c297'"
              :text="panelStatus?.state == '5' ? '离线' : '在线'" />

            <a-badge v-show="deviceType == 0" :color="panelStatus?.uavState == '18' ? '#ff4d4f' : '#00c297'"
              :text="panelStatus?.uavState == '18' ? '离线' : '在线'" />
          </div>
          <div class="title3">
            <div class="textBox" v-show="deviceType == 3">
              {{ ['空闲中', '现场调试', '远程调试', '固件升级中', '作业中'][panelStatus?.state] }}
            </div>

            <div class="textBox" :class="{ 'greyOut': panelStatus?.uavState == 18 }" v-show="deviceType == 0">
              {{ ['待机', '起飞准备',
                '起飞准备完毕', '手动飞行', '自动起飞', '航线飞行', '全景拍照',
                '智能跟随', 'ADS-B躲避', '自动返航', '自动降落', '强制降落', '三桨叶降落', '升级中', '未连接', 'APAS', '虚拟摇杆状态', '指令飞行',
                '离线'][panelStatus?.uavState] }}
            </div>
          </div>
          <div class="refreshData" @click="refreshData">
            <sync-outlined :spin="refreshDataStatus" />
          </div>
        </div>
      </div>

      <div v-show="deviceType == 3" class="airportBox">
        <div class="equipInformBox">
          <div class="left">
            <div class="img">
              <Image :preview="false" :src="airport"></Image>
            </div>
            <div class="title">
              <div class="title1">{{ DeviceStatus?.deviceName }}</div>
              <div class="title2">固件版本:{{ DeviceStatus?.dockShadow.firmwareVersion }}</div>
            </div>
          </div>
          <div class="right">
            <div>铭牌 SN:</div>
            <TypographyParagraph copyable :content="DeviceStatus?.deviceSn">
              <template #copyableIcon="{ copied }">
                <copy-outlined style="color: #acbdcf;" v-if="!copied" key="copy-icon" />
                <SmileFilled v-else key="copied-icon" />
              </template>
            </TypographyParagraph>
            <!-- {{ DeviceStatus?.deviceSn }} <copy-outlined /> -->
          </div>
        </div>
        <div class="deviceDetailBox">
          <a-row type="flex" :gutter="13">
            <a-col :span="6" :order="4" v-for="item in airportOverStatus">
              <div class="Box">
                <div class="title">{{ item.name }}</div>
                <div class="text">{{ item.value }}</div>
              </div>
            </a-col>
          </a-row>
        </div>
        <div class="controlBox">
          <!-- <div class="title"></div> -->
          <a-divider>机场控制</a-divider>
          <a-row type="flex" :gutter="13">
            <a-col :span="8" :order="4">
              <div class="Box">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/controlPanel_icon1.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">机场系统</div>
                    <div class="text">{{ airportControlStatus.airportSystem }}</div>
                  </div>
                  <a-button class="but" :loading="buttonLoadState.airportSystem" @click="restartSystem"
                    :disabled="allDisabled">重启</a-button>
                </div>
              </div>
            </a-col>

            <a-col :span="8" :order="4">
              <div class="Box" :class="{ 'gray-div': airportControlStatus.coverState == 0 }">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/controlPanel_icon2.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">舱盖</div>
                    <div class="text">{{ ['关闭', '打开', '半开', '舱盖状态异常'][airportControlStatus.coverState] || '---' }}</div>
                  </div>
                  <a-button class="but" :loading="buttonLoadState.coverState"
                    @click="openHatch(airportControlStatus.coverState)" :disabled="allDisabled">{{
                      ['开启', '关闭'][airportControlStatus.coverState]
                    }}</a-button>
                </div>
              </div>
            </a-col>

            <a-col :span="8" :order="4">
              <div class="Box" :class="{ 'gray-div': airportControlStatus.putterState == 0 }">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/controlPanel_icon3.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">推杆</div>
                    <div class="text">{{ ['关闭', '打开', '半开', '推杆状态异常'][airportControlStatus.putterState] || '' }}</div>
                  </div>
                  <a-button class="but" :loading="buttonLoadState.putterState"
                    @click="openPutter(airportControlStatus.putterState)" :disabled="allDisabled">{{
                      airportControlStatus.putterState == 0 ? '展开' : '关闭'
                    }}</a-button>
                </div>
              </div>
            </a-col>

            <a-col :span="8" :order="4">
              <div class="Box" :class="{ 'gray-div': airportControlStatus.airConditionerState == 0 }">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/controlPanel_icon4.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">空调</div>
                    <div class="text">{{
                      ['空闲模式', '制冷模式', '制热模式', '除湿模式', '制冷退出模式', '制热退出模式', '除湿退出模式', '制冷准备模式', '制热准备模式',
                        '除湿准备模式'][airportControlStatus.airConditionerState] || '---'
                    }}</div>
                  </div>
                  <a-button class="but" :loading="buttonLoadState.airConditionerState" :disabled="allDisabled"
                    @click="airConduit(airportControlStatus.airConditionerState)">{{
                      airportControlStatus.airConditionerState == 0 ? '开启' : '关闭'
                    }}</a-button>
                </div>
              </div>
            </a-col>

            <a-col :span="8" :order="4">
              <div class="Box" :class="{ 'gray-div': airportControlStatus.alarmState == 0 }">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/controlPanel_icon5.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">机场声光报警</div>
                    <div class="text">{{ ['关闭', '开启'][airportControlStatus.alarmState] || '---' }}</div>
                  </div>
                  <a-button class="but" :loading="buttonLoadState.alarmState" :disabled="allDisabled"
                    @click="airportAcousticItAlarm(airportControlStatus.alarmState)">{{
                      airportControlStatus.alarmState == 0 ? '开启' : '关闭' }}</a-button>
                </div>
              </div>
            </a-col>

            <a-col :span="8" :order="4">
              <div class="Box">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/controlPanel_icon6.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">机场存储</div>
                    <div class="text">{{ airportControlStatus.airportStorage || '---' }}</div>
                  </div>
                  <a-button class="but" :loading="buttonLoadState.airportStorage" :disabled="allDisabled"
                    @click="airportFormat">
                    格式化
                  </a-button>
                </div>
              </div>
            </a-col>

          </a-row>
        </div>
      </div>

      <div v-show="deviceType == 0" class="droneBox">
        <div class="equipInformBox">
          <div class="left">
            <div class="img">
              <Image :preview="false" :src="drone"></Image>
            </div>
            <div class="title">
              <div class="title1">{{ navData?.deviceName }}</div>
              <div class="title2">
                <div class="textBox" style="margin-bottom: 12px;">
                  <div class="title">左电池SN：</div>
                  <div class="text">
                    <TypographyParagraph copyable :content="navData?.aircraftShadow?.battery.batteries[0].sn">
                      <template #copyableIcon="{ copied }">
                        <copy-outlined style="color: #acbdcf;" v-if="!copied" key="copy-icon" />
                        <SmileFilled v-else key="copied-icon" />
                      </template>
                    </TypographyParagraph>
                  </div>
                </div>

                <div class="textBox">
                  <div class="title">右电池SN：</div>
                  <div class="text">
                    <TypographyParagraph copyable :content="navData?.aircraftShadow?.battery.batteries[1].sn">
                      <template #copyableIcon="{ copied }">
                        <copy-outlined style="color: #acbdcf;" v-if="!copied" key="copy-icon" />
                        <SmileFilled v-else key="copied-icon" />
                      </template>
                    </TypographyParagraph>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="right">
            <div class="title">铭牌 SN:</div>
            <div class="text">
              <TypographyParagraph copyable :content="navData?.deviceSn">
                <template #copyableIcon="{ copied }">
                  <copy-outlined style="color: #acbdcf;" v-if="!copied" key="copy-icon" />
                  <SmileFilled v-else key="copied-icon" />
                </template>
              </TypographyParagraph>
            </div>
          </div>
        </div>
        <div class="deviceDetailBox">
          <a-row type="flex" :gutter="13">
            <a-col :span="6" :order="4">
              <div class="Box">
                <div class="title">累计运行时长</div>
                <div class="text">{{ convertToMinOrHour(navData?.aircraftShadow?.totalFlightTime) }}</div>
              </div>
            </a-col>

            <a-col :span="6" :order="4">
              <div class="Box">
                <div class="title">飞行架次</div>
                <div class="text">{{ navData?.aircraftShadow?.totalFlightSorties }}架次</div>
              </div>
            </a-col>

            <a-col :span="6" :order="4">
              <div class="Box">
                <div class="title">图传</div>
                <div class="text">-dB</div>
              </div>
            </a-col>

            <a-col :span="6" :order="4">
              <div class="Box">
                <div class="title">搜星状态</div>
                <div class="text">{{
                  (navData?.aircraftShadow?.positionState && JSON.parse(navData.aircraftShadow.positionState).rtk_number
                    != null && JSON.parse(navData.aircraftShadow.positionState).gps_number != null) ?
                  JSON.parse(navData.aircraftShadow.positionState).rtk_number
                  + JSON.parse(navData.aircraftShadow.positionState).gps_number : ''
                }}</div>
              </div>
            </a-col>
          </a-row>
        </div>
        <div class="batteryInformBox">
          <a-row type="flex" :gutter="9">
            <a-col :span="12" :order="2">
              <div class="left">
                <div class="leftHeadBox">
                  <div class="text">左电池</div>
                  <div class="battery">
                    <div class="electroQuantity">{{ droneBattery.leftBattery }}%
                    </div>
                    <Power :percent="droneBattery.leftBattery"></Power>
                  </div>
                </div>
                <div class="batteryBox">
                  <div class="left">
                    <div class="topBox">
                      <div class="title">循环次数</div>
                      <div class="val">{{ navData?.aircraftShadow?.battery.batteries[0].loop_times }}次</div>
                    </div>
                    <div class="BotBox">
                      <div class="title">电压</div>
                      <div class="val">{{ (navData?.aircraftShadow?.battery.batteries[0].voltage / 1000).toFixed(1) }}V
                      </div>
                    </div>
                  </div>

                  <div class="left">
                    <div class="topBox">
                      <div class="title">高电量存储</div>
                      <div class="val">{{ navData?.aircraftShadow?.battery.batteries[0].high_voltage_storage_days }}天
                      </div>
                    </div>
                    <div class="BotBox">
                      <div class="title">温度</div>
                      <div class="val">{{ navData?.aircraftShadow?.battery.batteries[0].temperature }}°C</div>
                    </div>
                  </div>

                </div>
              </div>
            </a-col>

            <a-col :span="12" :order="2">
              <div class="left">
                <div class="leftHeadBox">
                  <div class="text">右电池</div>
                  <div class="battery">
                    <div class="electroQuantity">{{ droneBattery.rightBattery }}%</div>
                    <Power :percent="droneBattery.rightBattery"></Power>
                  </div>
                </div>
                <div class="batteryBox">
                  <div class="left">
                    <div class="topBox">
                      <div class="title">循环次数</div>
                      <div class="val">{{ navData?.aircraftShadow?.battery.batteries[1].loop_times }}次</div>
                    </div>
                    <div class="BotBox">
                      <div class="title">电压</div>
                      <div class="val">{{ (navData?.aircraftShadow?.battery.batteries[1].voltage / 1000).toFixed(1) }}V
                      </div>
                    </div>
                  </div>

                  <div class="left">
                    <div class="topBox">
                      <div class="title">高电量存储</div>
                      <div class="val">{{ navData?.aircraftShadow?.battery.batteries[1].high_voltage_storage_days }}天
                      </div>
                    </div>
                    <div class="BotBox">
                      <div class="title">温度</div>
                      <div class="val">{{ navData?.aircraftShadow?.battery.batteries[1].temperature }}°C</div>
                    </div>
                  </div>

                </div>
              </div>
            </a-col>
          </a-row>
        </div>
        <div class="aircraftSetupBox">
          <a-row type="flex" :gutter="9">
            <a-col :span="12" :order="2">
              <div class="aircraftSetup">
                <div class="title">飞行器夜航灯</div>
                <div class="switchBox">
                  <div class="title">{{ aircraftSwitch.nightLight ? '关闭' : '开启' }}</div>
                  <a-switch v-model:checked="aircraftSwitch.nightLight" @click="aircraftNightLightClick"
                    :disabled="allDisabled" :loading="nightLightSwitch" />
                </div>
              </div>
            </a-col>

            <a-col :span="12" :order="2">
              <div class="aircraftSetup">
                <div class="title">
                  <div class="text">避障</div>
                  <ExclamationCircleOutlined />
                </div>
                <div class="switchBox">
                  <div class="title">{{ aircraftSwitch.avoidObstacle ? '关闭' : '开启' }}</div>
                  <a-switch :disabled="allDisabled" @click="obstacleAvoid" v-model:checked="aircraftSwitch.avoidObstacle"
                    :loading="avoidObstacleSwitch" />
                </div>
              </div>
            </a-col>

            <a-col :span="12" :order="2">
              <div class="aircraftSetup">
                <div class="title">
                  <div class="text">限高</div>
                  <ExclamationCircleOutlined />
                </div>
                <div class="switchBox">
                  <a-input-number class="inp" :min="20" :max="1500" :disabled="allDisabled" @change="heightLimitChange"
                    v-model:value="aircraftSwitch.heightLimit"></a-input-number>
                </div>
              </div>
            </a-col>

            <a-col :span="12" :order="2">
              <div class="aircraftSetup">
                <div class="title">
                  <div class="text">限远</div>
                  <ExclamationCircleOutlined />
                </div>
                <div class="switchBox">
                  <a-input-number class="inp" :min="15" :max="8000" @change="distanceLimitChange" :disabled="allDisabled"
                    v-model:value="aircraftSwitch.distanceLimit"></a-input-number>
                </div>
              </div>
            </a-col>

            <a-col :span="12" :order="2">
              <div class="aircraftSetup">
                <div class="title">
                  <div class="text">备降转移高</div>
                  <ExclamationCircleOutlined />
                </div>
                <div class="switchBox">
                  <a-input-number class="inp" @change="safeLandHeightChange" :disabled="allDisabled"
                    v-model:value="aircraftSwitch.safeLandHeight"></a-input-number>
                </div>
              </div>
            </a-col>

            <a-col :span="12" :order="2">
              <div class="aircraftSetup">
                <div class="title">
                  <div class="text">运行模式</div>
                  <ExclamationCircleOutlined />
                </div>
                <div class="switchBox">
                  <a-select class="inp" @change="batteryStoreModeChange" :disabled="allDisabled"
                    v-model:value="aircraftSwitch.batteryStoreMode" :options="overMode"></a-select>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>
        <div class="controlBox">
          <!-- <div class="title"></div> -->
          <a-divider>机场控制</a-divider>
          <a-row type="flex" :gutter="13">
            <a-col :span="8" :order="4">
              <div class="Box" :class="{ 'gray-div': airportControlStatus.deviceOnlineStatus == 0 }">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/navControl_icon1.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">飞行电源</div>
                    <div class="text">{{ ['关机', '开机'][airportControlStatus.deviceOnlineStatus] }}</div>
                  </div>
                  <a-button class="but" :loading="buttonLoadState.deviceOnlineStatus" :disabled="allDisabled"
                    @click="turnNav(airportControlStatus.deviceOnlineStatus)">{{ airportControlStatus.deviceOnlineStatus
                      == 0 ? '开机' : '关机' }}</a-button>
                </div>
              </div>
            </a-col>

            <a-col :span="8" :order="4">
              <div class="Box" :class="{ 'gray-div': airportControlStatus.droneChargeState == 0 }">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/navControl_icon2.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">飞行器充电</div>
                    <div class="text">{{ ['空闲', '充电中'][airportControlStatus.droneChargeState] }}</div>
                  </div>
                  <a-button class="but" :disabled="allDisabled" :loading="buttonLoadState.droneChargeState"
                    @click="aircraftCharge">充电</a-button>
                </div>
              </div>
            </a-col>

            <a-col :span="8" :order="4">
              <div class="Box" :class="{ 'gray-div': airportControlStatus.maintenanceState == 0 }">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/navControl_icon3.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">电池保养</div>
                    <div class="text">{{ ['无需保养', '待保养', '正在保养'][airportControlStatus.maintenanceState] }}</div>
                  </div>
                  <a-button class="but" :loading="buttonLoadState.maintenanceState" :disabled="allDisabled"
                    @click="batteryMainTen(airportControlStatus.maintenanceState)">保养</a-button>
                </div>
              </div>
            </a-col>

            <a-col :span="8" :order="4">
              <div class="Box" :class="{ 'gray-div': airportControlStatus.wirelessLink == 0 }">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/navControl_icon4.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">图传增强</div>
                    <div class="text">{{ ['SDR 模式', '4G 融合模式'][airportControlStatus.wirelessLink] }}</div>
                  </div>
                  <a-button class="but" :disabled="allDisabled" :loading="buttonLoadState.wirelessLink"
                    @click="enhance(airportControlStatus.wirelessLink)">{{
                      airportControlStatus.wirelessLink == 0 ? '开启' : '关闭'
                    }}</a-button>
                </div>
              </div>
            </a-col>

            <a-col :span="8" :order="4">
              <div class="Box">
                <div class="left">
                  <img src="@/assets/icons/deviceManageList/equipModal/navControl_icon5.jpg" />
                </div>
                <div class="right">
                  <div class="titleBox">
                    <div class="title">飞行器存储</div>
                    <div class="text">{{ airportControlStatus.aircraftStorage }}</div>
                  </div>
                  <a-button class="but" :disabled="allDisabled" @click="aircraftFormat"
                    :loading="buttonLoadState.aircraftStorage">
                    格式化
                  </a-button>
                </div>
              </div>
            </a-col>

          </a-row>
        </div>
      </div>
    </div>

  </Modal>
</template>
<script lang="ts" setup>
import { ref, computed, defineProps, watch, defineEmits, reactive, onMounted, onBeforeUnmount } from 'vue';
import { CopyOutlined, SmileFilled, ExclamationCircleOutlined, SyncOutlined } from '@ant-design/icons-vue';
import { Modal } from 'ant-design-vue';
import { Image, TypographyParagraph } from 'ant-design-vue';
import Power from '@/components/power/index.vue';
import { deviceApi } from './data.api';
import { onWebSocket, offWebSocket, useMyWebSocket } from '@/hooks/web/useWebSocket.ts'
import { message } from 'ant-design-vue';

//svg 图片导入
import drone_icon0 from '@/assets/icons/deviceManageList/drone_icon0.svg';
import drone_icon1 from '@/assets/icons/deviceManageList/drone_icon1.svg';
import airport_icon0 from '@/assets/icons/deviceManageList/airport_icon0.svg';
import airport_icon1 from '@/assets/icons/deviceManageList/airport_icon1.svg';
import airport from '@/assets/icons/deviceManageList/equipModal/airport.svg';
import drone from '@/assets/icons/deviceManageList/equipModal/drone.svg';
const visible = ref<boolean>(false);

let allDisabled = ref<boolean>(false) //全部按钮禁止状态
let deviceType = ref(3)  // 设备类型 0机场 1无人机  设备类型 0:飞行器 1:负载类,2:遥控器.3:机场
let equipDebug = ref<boolean>(false) //设备调试总开关
let equipDebugSwitch = ref<boolean>(false) //

let nightLightSwitch = ref<boolean>(false)
let avoidObstacleSwitch = ref<boolean>(false)

let refreshDataStatus = ref<boolean>(false) //刷新数据icon 是否旋转

let aircraftSwitch = reactive({
  nightLight: false,
  avoidObstacle: false,
  heightLimit: '',
  distanceLimit: '',
  batteryStoreMode: null,
  safeLandHeight: null
})
let overMode = ref([
  {
    value: '1',
    label: '计划模式',
  },
  {
    value: '2',
    label: '待命模式',
  },
])
//机场运行数据列表
let airportOverStatus = ref([
  {
    name: '累计运行时长',
    value: '-',
  },
  {
    name: '作业架次',
    value: '-',
  },
  {
    name: '机场搜星',
    value: '-',
  },
  {
    name: '标定状态',
    value: '-',
  },
  //------------------
  {
    name: '供电电压',
    value: '-',
  },
  {
    name: '网络',
    value: '-',
  },
  {
    name: '备降点',
    value: '-',
  },
  {
    name: '空调状态',
    value: '-',
  },
  //------------------------
  {
    name: '蓄电池开关',
    value: '-',
  },
  {
    name: '蓄电池电压',
    value: '-',
  },
  {
    name: '蓄电池温度',
    value: '-',
  },
  {
    name: '舱内温度',
    value: '-',
  },
  //---------------------------
  {
    name: '舱内湿度',
    value: '-',
  },
  {
    name: '舱外温度',
    value: '-',
  },
  {
    name: '雨量',
    value: '-',
  },
  {
    name: '风速',
    value: '-',
  },
])
//面板的状态
let panelStatus = reactive({
  state: null,
  uavState: null,
})

//无人机电量信息
let droneBattery = reactive({
  leftBattery: null,  //左电池电量
  rightBattery: null
})

let airportControlStatus = reactive({
  coverState: null, //{"0":"关闭","1":"打开","2":"半开","3":"舱盖状态异常"}
  putterState: null, //{"0":"关闭","1":"打开","2":"半开","3":"推杆状态异常"}
  airConditionerState: null, //{"0":"空闲模式（无制冷、制热、除湿等）","1":"制冷模式","2":"制热模式","3":"除湿模式","4":"制冷退出模式","5":"制热退出模式","6":"除湿退出模式","7":"制冷准备模式","8":"制热准备模式","9":"除湿准备模式"}
  alarmState: null,//{"0":"声光报警关闭","1":"声光报警开启"}
  airportSystem: '---',
  //------------------------------
  droneChargeState: null,  //{"0":"空闲","1":"充电中"}
  maintenanceState: null,  //{"0":"无需保养","1":"待保养","2":"正在保养"}
  wirelessLink: null,  //	{"0":"SDR 模式","1":"4G 融合模式"}
  aircraftStorage: '', // 飞行器存储
  deviceOnlineStatus: null, //{"0":"关机","1":"开机"}
  airportStorage: '',     //机场存储
})

let buttonLoadState = reactive({
  airportSystem: false,
  coverState: false,
  putterState: false,
  airConditionerState: false,
  alarmState: false,
  airportStorage: false,
  //-----------------
  droneChargeState: false,
  maintenanceState: false,
  wirelessLink: false,
  deviceOnlineStatus: false,
  aircraftStorage: false,
})

let DeviceStatus = ref() //机场数据
let navData = ref() //无人机数据
let webSocketStatus = ref(useMyWebSocket());  //当前websocket 的状态
let messages = ref([]) //websocket 监听到的消息

const emit = defineEmits();
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  deviceId: {
    type: String,
  },
  navEquipId: {
    type: String,
  },
  deviceSn: {
    type: Array,
  }
});

function afterClose() {
  emit('close')
  // DeviceStatus.value = null
  equipDebugSwitch.value = false
}

function switchEquip(type) {
  console.log(type);
  deviceType.value = type  //  设备面板切换
}

async function refreshData() {
  refreshDataStatus.value = true
  await queryDeviceStatus()
  await navEquipQuery()
  refreshDataStatus.value = false
}

async function RollRefreshData() {
  const res = await deviceApi.getShadow(props.deviceId)
  const NavRes = await deviceApi.getShadow(props.navEquipId)
  panelStatus.state = res.state
  airportOverStatus.value[0].value = convertToMinOrHour(res.dockShadow.accTime)
  airportOverStatus.value[1].value = res.dockShadow.jobNumber
  airportOverStatus.value[2].value = res.dockShadow.dockState.position_state.gps_number + res.dockShadow.dockState.position_state.rtk_number
  airportOverStatus.value[3].value = res.dockShadow.dockState.position_state.is_calibration == 0 ? '未标定' : '已标定'
  //-------------------------------
  airportOverStatus.value[4].value = (res.dockShadow.workingVoltage / 1000).toFixed(1) + 'V'
  airportOverStatus.value[5].value = res.dockShadow.dockState.network_state.rate.toFixed(2) + 'KB/s'
  airportOverStatus.value[6].value = res.dockShadow.dockState.alternate_land_point?.is_configured == 1 ? '已配置' : '未配置'
  const airConduitConduit = res.dockShadow.dockState.air_conditioner?.air_conditioner_state
  if (airConduitConduit == 0) {
    airportOverStatus.value[7].value = '空闲模式'
  } else if (airConduitConduit == 1) {
    airportOverStatus.value[7].value = '制冷模式'
  } else if (airConduitConduit == 2) {
    airportOverStatus.value[7].value = '制热模式'
  } else if (airConduitConduit == 3) {
    airportOverStatus.value[7].value = '除湿模式'
  } else if (airConduitConduit == 4) {
    airportOverStatus.value[7].value = '制冷退出模式'
  } else if (airConduitConduit == 5) {
    airportOverStatus.value[7].value = '制热退出模式'
  } else if (airConduitConduit == 6) {
    airportOverStatus.value[7].value = '除湿退出模式'
  } else if (airConduitConduit == 7) {
    airportOverStatus.value[7].value = '制冷准备模式'
  } else if (airConduitConduit == 8) {
    airportOverStatus.value[7].value = '制热准备模式'
  } else if (airConduitConduit == 9) {
    airportOverStatus.value[7].value = '除湿准备模式'
  }
  //--------------------------------
  airportOverStatus.value[8].value = res.dockShadow.backupBattery.switch == 1 ? '开启' : '关闭'
  airportOverStatus.value[9].value = (res.dockShadow.backupBattery.voltage / 1000).toFixed(1) + 'V'
  airportOverStatus.value[10].value = res.dockShadow.backupBattery.temperature + '°C'
  airportOverStatus.value[11].value = res.dockShadow.dockState.temperature + '°C' //0
  //-----------------------------
  airportOverStatus.value[12].value = res.dockShadow.dockState.humidity + '%'
  airportOverStatus.value[13].value = res.dockShadow.dockState.environment_temperature + '°C'
  airportOverStatus.value[14].value = res.dockShadow.dockState.rainfall == 0 ? '无雨' : res.dockShadow.dockState.rainfall == 1 ? '小雨' : res.dockShadow.dockState.rainfall == 2 ? '中雨' : res.dockShadow.dockState.rainfall == 3 ? '大雨' : res.dockShadow.dockState.rainfall
  airportOverStatus.value[15].value = res.dockShadow.dockState.wind_speed + 'm/s' //0

  droneBattery.leftBattery = NavRes.aircraftShadow?.battery.batteries[0].capacity_percent //飞机左电池电量
  droneBattery.rightBattery = NavRes.aircraftShadow?.battery.batteries[1].capacity_percent //飞机右电池电量
  airportControlStatus.aircraftStorage = `${convertKBToGB(NavRes.aircraftShadow.storage.used)}/${convertKBToGB(NavRes.aircraftShadow.storage.total)}GB`

  navData.value = NavRes
  panelStatus.uavState = NavRes.state
}

let timeRefreshData: ReturnType<typeof setInterval>;
//获取飞行参数 -- 拿到飞机飞行中的数据
function getrefreshData() {
  timeRefreshData = setInterval(() => {
    RollRefreshData()
  }, 3000)
}

watch(
  () => props.open,
  (newValue) => {
    visible.value = newValue;
    if (newValue) {
      queryDeviceStatus()
      navEquipQuery()

      getrefreshData()
    } else {
      if (timeRefreshData) {
        clearInterval(timeRefreshData)
        console.log('timeRefreshData 销毁')
      }
      DeviceStatus.value = null
    }
    console.log(newValue);
  },
)



function convertKBToGB(kb) {
  const gb = kb / (1024 * 1024); // 1 GB = 1024 MB, 1 MB = 1024 KB
  return gb.toFixed(2); // 四舍五入到两位小数
}

async function queryDeviceStatus() {
  const res = await deviceApi.getShadow(props.deviceId)
  //机场控制
  DeviceStatus.value = res
  panelStatus.state = res.state
  airportControlStatus.airportSystem = res.state != 5 ? '运行中' : '---'
  equipDebug.value = res.dockShadow.dockState.mode_code == 2 ? true : false
  allDisabled.value = res.dockShadow.dockState.mode_code == 2 ? false : true //111
  aircraftSwitch.safeLandHeight = res.dockShadow.dockState.alternate_land_point.safe_land_height
  airportControlStatus.coverState = res.dockShadow.dockState.cover_state
  airportControlStatus.putterState = res.dockShadow.dockState.putter_state
  airportControlStatus.airConditionerState = res.dockShadow.dockState.air_conditioner?.air_conditioner_state
  airportControlStatus.alarmState = res.dockShadow.dockState.alarm_state
  airportControlStatus.airportStorage = `${convertKBToGB(res.dockShadow.dockState.storage.used)}/${convertKBToGB(res.dockShadow.dockState.storage.total)}GB`
  //---------------------------
  //无人机控制

  airportControlStatus.droneChargeState = res.dockShadow.dockState.drone_charge_state.state
  airportControlStatus.maintenanceState = res.dockShadow.droneBatteryMaintenanceInfo.maintenance_state
  airportControlStatus.wirelessLink = res.dockShadow.wirelessLink.wireless_link.link_workmode
  //-------------------------
  airportOverStatus.value[0].value = convertToMinOrHour(res.dockShadow.accTime)
  airportOverStatus.value[1].value = res.dockShadow.jobNumber
  airportOverStatus.value[2].value = res.dockShadow.dockState.position_state.gps_number + res.dockShadow.dockState.position_state.rtk_number
  airportOverStatus.value[3].value = res.dockShadow.dockState.position_state.is_calibration == 0 ? '未标定' : '已标定'
  //-------------------------------
  airportOverStatus.value[4].value = (res.dockShadow.workingVoltage / 1000).toFixed(1) + 'V'
  airportOverStatus.value[5].value = res.dockShadow.dockState.network_state.rate.toFixed(2) + 'KB/s'
  airportOverStatus.value[6].value = res.dockShadow.dockState.alternate_land_point?.is_configured == 1 ? '已配置' : '未配置'
  const airConduitConduit = res.dockShadow.dockState.air_conditioner?.air_conditioner_state
  if (airConduitConduit == 0) {
    airportOverStatus.value[7].value = '空闲模式'
  } else if (airConduitConduit == 1) {
    airportOverStatus.value[7].value = '制冷模式'
  } else if (airConduitConduit == 2) {
    airportOverStatus.value[7].value = '制热模式'
  } else if (airConduitConduit == 3) {
    airportOverStatus.value[7].value = '除湿模式'
  } else if (airConduitConduit == 4) {
    airportOverStatus.value[7].value = '制冷退出模式'
  } else if (airConduitConduit == 5) {
    airportOverStatus.value[7].value = '制热退出模式'
  } else if (airConduitConduit == 6) {
    airportOverStatus.value[7].value = '除湿退出模式'
  } else if (airConduitConduit == 7) {
    airportOverStatus.value[7].value = '制冷准备模式'
  } else if (airConduitConduit == 8) {
    airportOverStatus.value[7].value = '制热准备模式'
  } else if (airConduitConduit == 9) {
    airportOverStatus.value[7].value = '除湿准备模式'
  }
  //--------------------------------
  airportOverStatus.value[8].value = res.dockShadow.backupBattery.switch == 1 ? '开启' : '关闭'
  airportOverStatus.value[9].value = (res.dockShadow.backupBattery.voltage / 1000).toFixed(1) + 'V'
  airportOverStatus.value[10].value = res.dockShadow.backupBattery.temperature + '°C'
  airportOverStatus.value[11].value = res.dockShadow.dockState.temperature + '°C' //0
  //-----------------------------
  airportOverStatus.value[12].value = res.dockShadow.dockState.humidity + '%'
  airportOverStatus.value[13].value = res.dockShadow.dockState.environment_temperature + '°C'
  airportOverStatus.value[14].value = res.dockShadow.dockState.rainfall == 0 ? '无雨' : res.dockShadow.dockState.rainfall == 1 ? '小雨' : res.dockShadow.dockState.rainfall == 2 ? '中雨' : res.dockShadow.dockState.rainfall == 3 ? '大雨' : res.dockShadow.dockState.rainfall
  airportOverStatus.value[15].value = res.dockShadow.dockState.wind_speed + 'm/s' //0



  console.log(DeviceStatus.value, 'DeviceStatus')
}

async function navEquipQuery() {
  const res = await deviceApi.getShadow(props.navEquipId)
  droneBattery.leftBattery = res.aircraftShadow?.battery.batteries[0].capacity_percent //飞机左电池电量
  droneBattery.rightBattery = res.aircraftShadow?.battery.batteries[1].capacity_percent //飞机右电池电量
  aircraftSwitch.nightLight = res.aircraftShadow.nightLightsState == 0 ? false : true
  aircraftSwitch.heightLimit = res.aircraftShadow.heightLimit //飞行器限高
  aircraftSwitch.distanceLimit = res.aircraftShadow.distanceLimitStatus.distance_limit //飞行器限远
  airportControlStatus.aircraftStorage = `${convertKBToGB(res.aircraftShadow.storage.used)}/${convertKBToGB(res.aircraftShadow.storage.total)}GB`
  //-----------------
  navData.value = res
  panelStatus.uavState = res.state
  airportControlStatus.deviceOnlineStatus = res.state == 18 ? 0 : 1
}


function convertToMinOrHour(seconds) {
  if (seconds >= 3600) {
    return `${Math.floor(seconds / 3600)}h`;
  } else if (seconds >= 60) {
    return `${Math.floor(seconds / 60)}min`;
  } else {
    return `${seconds}s`;
  }
}


// 添加WebSocket消息监听器
function addWebSocketListener() {
  console.log('监听websocket')
  onWebSocket((data) => {
    messages.value = data
    console.log(messages.value, '监听到消息')
  });
}

// 移除WebSocket消息监听器
function removeWebSocketListener() {
  offWebSocket((data) => {
    console.log(data, '移除WebSocket消息监听器')
    messages.value = ''
  });
  // console.log('移除WebSocket消息监听器')
};

async function addExecuteInstruct(type, instuct, action) {
  //type  机场传3  无人机传0  instuct 设备指令  action 指令动作
  // if (action) {
  //   await executeInstruct({
  //     deviceId: type == 3 ? props.deviceId : type == 0 ? props.navEquipId : '',
  //     deviceSn: type == 3 ? props.deviceSn[0] : type == 0 ? props.deviceSn[1] : '',
  //     instuct: instuct,
  //     reqId: localStorage.getItem('wsClientId'),
  //     action
  //   })
  // } else {
  //   await executeInstruct({
  //     deviceId: type == 3 ? props.deviceId : type == 0 ? props.navEquipId : '',
  //     deviceSn: type == 3 ? props.deviceSn[0] : type == 0 ? props.deviceSn[1] : '',
  //     instuct: instuct,
  //     reqId: localStorage.getItem('wsClientId')
  //   })
  // }

  const commonParams = {
    deviceId: type === 3 ? props.deviceId : type === 0 ? props.navEquipId : '',
    deviceSn: type === 3 ? props.deviceSn[0] : type === 0 ? props.deviceSn[1] : '',
    instuct,
    reqId: localStorage.getItem('wsClientId'),
  };

  const params = action ? { ...commonParams, action } : commonParams;

  await deviceApi.executeInstruct(params);

}


// 远程调试按钮
async function equipDebugClick(event) {
  equipDebugSwitch.value = true
  try {
    const unwatch = watch(messages, (newValue) => {
      console.log(newValue, 'messages123456666')
      if (newValue.data.output.status == "ok") {
        equipDebugSwitch.value = false
        allDisabled.value = false
        if (event) {
          panelStatus.state = 2
        } else {
          panelStatus.state = 0
        }
        console.log('执行完毕了-------------------------')
        // 停止监听 messages.value 的变化
        unwatch();
      } else {
        equipDebugSwitch.value = false
        equipDebug.value = false
      }
    })

    if (event) {
      await addExecuteInstruct(3, 'debug_mode_open')
    } else {
      await addExecuteInstruct(3, 'debug_mode_close')
    }
  } catch {
    equipDebugSwitch.value = false
    equipDebug.value = false
  }
}

//打开空调
function airConduit(type) {
  try {
    let hasFinished = false;
    allDisabled.value = true;
    buttonLoadState.airConditionerState = true
    const unwatch = watch(messages, (newValue) => {
      if (newValue.data.output.status == "ok" && !hasFinished) {
        hasFinished = true;
        allDisabled.value = false;
        buttonLoadState.airConditionerState = false;
        if (type == 0) {
          airportControlStatus.airConditionerState = 1
          airportOverStatus.value[7].value = '制冷模式'
        }

        if (type == 1) {
          airportControlStatus.airConditionerState = 0
          airportOverStatus.value[7].value = '空闲模式'
        }

        unwatch();
      }
    })

    if (type == 0) {
      // 空调当前是空闲模式  需要开启空调
      addExecuteInstruct(3, 'air_conditioner_mode_switch', { action: 1 })
    } else {
      // 如果不是空闲模式  直接关闭空调
      addExecuteInstruct(3, 'air_conditioner_mode_switch', { action: 0 })
    }
  } catch {
    allDisabled.value = false;
    buttonLoadState.airConditionerState = false;
  }


}

//打开舱盖
async function openHatch(type) {
  // 定义一个标志来表示是否已经结束
  let hasFinished = false;
  allDisabled.value = true;
  buttonLoadState.coverState = true
  // 创建一个监听器来监视 messages.value 的变化
  const unwatch = watch(messages, (newValue) => {
    if (newValue.data.output.status == "ok" && !hasFinished) {
      hasFinished = true;
      allDisabled.value = false;
      buttonLoadState.coverState = false
      if (type == 0) {
        airportControlStatus.coverState = 1
      }
      if (type == 1) {
        airportControlStatus.coverState = 0
      }
      console.log('执行完毕了-------------------------')
      // 停止监听 messages.value 的变化
      unwatch();
    }
    console.log(newValue, '监听消息newValue')
  })

  if (type == 0) {
    //当前是关闭状态   需要开启舱盖
    await addExecuteInstruct(3, 'cover_open')
  }
  if (type == 1) {
    //当前是打开状态  需要关闭舱盖
    await addExecuteInstruct(3, 'cover_close')
  }
}

//打开推杆
async function openPutter(type) {
  // 定义一个标志来表示是否已经结束
  let hasFinished = false;
  allDisabled.value = true;
  buttonLoadState.putterState = true


  const unwatch = watch(messages, (newValue) => {
    if (newValue.data.output.status == "ok" && !hasFinished) {
      hasFinished = true;
      allDisabled.value = false;
      buttonLoadState.putterState = false
      if (type == 0) {
        airportControlStatus.putterState = 1
      } else {
        airportControlStatus.putterState = 0
      }
      console.log('执行完毕了-------------------------')
      // 停止监听 messages.value 的变化
      unwatch();
    }
  })

  if (type == 0) {
    //当前是关闭状态   需要展开推杆
    await addExecuteInstruct(3, 'putter_open')
  }
  if (type == 1 || type == 2) {
    //当前是展开状态  需要关闭推杆
    await addExecuteInstruct(3, 'putter_close')
  }
}

//机场存储格式化
async function airportFormat() {
  let hasFinished = false;
  allDisabled.value = true;
  buttonLoadState.airportStorage = true;
  const unwatch = watch(messages, (newValue) => {
    if (newValue.data.output.status == "ok" && !hasFinished) {
      hasFinished = true;
      allDisabled.value = false;
      buttonLoadState.airportStorage = false
      queryDeviceStatus()
      console.log('执行完毕了-------------------------')
      // 停止监听 messages.value 的变化
      unwatch();
    }
  })

  await addExecuteInstruct(3, 'device_format')

}

//飞行器存储格式化
async function aircraftFormat() {
  let hasFinished = false;
  allDisabled.value = true;
  buttonLoadState.aircraftStorage = true;
  const unwatch = watch(messages, (newValue) => {
    if (newValue.data.output.status == "ok" && !hasFinished) {
      hasFinished = true;
      allDisabled.value = false;
      buttonLoadState.aircraftStorage = false
      navEquipQuery()
      console.log('执行完毕了-------------------------')
      // 停止监听 messages.value 的变化
      unwatch();
    }
  })

  await addExecuteInstruct(3, 'drone_format')
}

//机场声光报警
async function airportAcousticItAlarm(type) {
  try {
    let hasFinished = false;
    allDisabled.value = true;
    buttonLoadState.alarmState = true
    const unwatch = watch(messages, (newValue) => {
      if (newValue.data.output.status == "ok" && !hasFinished) {
        hasFinished = true;
        allDisabled.value = false;
        buttonLoadState.alarmState = false
        if (type == 0) {
          airportControlStatus.alarmState = 1
        } else {
          airportControlStatus.alarmState = 0
        }
        console.log('执行完毕了-------------------------')
        // 停止监听 messages.value 的变化
        unwatch();
      }
    })

    if (type == 0) {
      //当前是关闭状态 需要开启
      await addExecuteInstruct(3, 'alarm_state_switch', { action: 1 })
    }

    if (type == 1) {
      //当前开启   需要关闭
      await addExecuteInstruct(3, 'alarm_state_switch', { action: 0 })
    }
  } catch {
    hasFinished = true;
    allDisabled.value = false;
    buttonLoadState.alarmState = false
  }
}

//重启系统
async function restartSystem() {
  let hasFinished = false;
  allDisabled.value = true;
  buttonLoadState.airportSystem = true
  airportControlStatus.airportSystem = '重启中...'
  const unwatch = watch(messages, (newValue) => {
    if (newValue.data.output.status == "ok" && !hasFinished) {

      hasFinished = true;
      allDisabled.value = false;
      buttonLoadState.airportSystem = false
      console.log('执行完毕了-------------------------')
      airportControlStatus.airportSystem = '运行中'
      // 停止监听 messages.value 的变化
      unwatch();
    }
  })

  await addExecuteInstruct(3, 'device_reboot')
}

//飞行电源
async function turnNav(type) {
  let hasFinished = false;
  allDisabled.value = true;
  buttonLoadState.deviceOnlineStatus = true
  const unwatch = watch(messages, (newValue) => {
    if (newValue.data.output.status == "ok" && !hasFinished) {
      hasFinished = true;
      allDisabled.value = false;
      buttonLoadState.deviceOnlineStatus = false
      if (type == 0) {
        airportControlStatus.deviceOnlineStatus = 1
      } else {
        airportControlStatus.deviceOnlineStatus = 0
      }
      console.log('执行完毕了-------------------------')
      // 停止监听 messages.value 的变化
      unwatch();
    }
  })

  if (type == 0) {
    await addExecuteInstruct(3, 'drone_open')
  } else {
    await addExecuteInstruct(3, 'drone_close')
  }
}

//飞行器充电
async function aircraftCharge() {
  try {
    let hasFinished = false;
    allDisabled.value = true;
    buttonLoadState.droneChargeState = true
    const unwatch = watch(messages, (newValue) => {
      if (newValue.data.output.status == "ok" && !hasFinished) {
        hasFinished = true;
        allDisabled.value = false;
        buttonLoadState.droneChargeState = false
        airportControlStatus.droneChargeState = 1
        console.log('执行完毕了-------------------------')
        // 停止监听 messages.value 的变化
        unwatch();
      }
    })

    await addExecuteInstruct(3, 'charge_open')
  } catch {
    allDisabled.value = false;
    buttonLoadState.droneChargeState = false
  }

}

//电池保养
async function batteryMainTen(type) {
  try {
    let hasFinished = false;
    allDisabled.value = true;

    const unwatch = watch(messages, (newValue) => {
      if (newValue.data.output.status == "ok" && !hasFinished) {
        hasFinished = true;
        allDisabled.value = false;
        if (type == 1) {
          airportControlStatus.maintenanceState = 2
        }
        if (type == 2) {
          airportControlStatus.maintenanceState = 1
        }
        console.log('执行完毕了-------------------------')
        // 停止监听 messages.value 的变化
        unwatch();
      }
    })

    if (type == 0) {
      message.warning('无需保养');
      return;
    }
    if (type == 1) {
      await addExecuteInstruct(3, 'battery_maintenance_switch', { action: 1 })
    }
    if (type == 2) {
      await addExecuteInstruct(3, 'battery_maintenance_switch', { action: 0 })
    }
  } catch { }

}

//图传增强
async function enhance(type) {
  let hasFinished = false;
  try {
    allDisabled.value = true;
    buttonLoadState.wirelessLink = true
    const unwatch = watch(messages, (newValue) => {
      if (newValue.data.output.status == "ok" && !hasFinished) {
        hasFinished = true;
        allDisabled.value = false;
        if (type == 0) {
          airportControlStatus.wirelessLink = 1
        }
        if (type == 1) {
          airportControlStatus.wirelessLink = 0
        }
        buttonLoadState.wirelessLink = false
        console.log('执行完毕了-------------------------')
        // 停止监听 messages.value 的变化
        unwatch();
      }
    })

    if (type == 0) {
      await addExecuteInstruct(3, 'battery_maintenance_switch', { action: 1 })
    }

    if (type == 1) {
      await addExecuteInstruct(3, 'battery_maintenance_switch', { action: 0 })
    }
  } catch {
    hasFinished = true;
    allDisabled.value = false;
    buttonLoadState.wirelessLink = false
  }

}

//飞行器夜航灯
async function aircraftNightLightClick(event) {
  let hasFinished = false;
  nightLightSwitch.value = true;
  allDisabled.value = true;
  try {
    const unwatch = watch(messages, (newValue) => {
      if (newValue.data.night_lights_state.result == 0 && !hasFinished) {
        hasFinished = true;
        allDisabled.value = false;
        nightLightSwitch.value = false;
        console.log('执行完毕了-------------------------')
        // 停止监听 messages.value 的变化
        unwatch();
      } else if (newValue.data.night_lights_state.result != 0) {
        //执行失败
        nightLightSwitch.value = false;
        aircraftSwitch.nightLight = false
        allDisabled.value = false;
      }

    })

    if (event) {
      await addExecuteInstruct(3, 'night_lights_state', { night_lights_state: 1 })
    } else {
      await addExecuteInstruct(3, 'night_lights_state', { night_lights_state: 0 })
    }
  } catch {
    nightLightSwitch.value = false;
    aircraftSwitch.nightLight = false
    allDisabled.value = false;
  }
}

//避障
async function obstacleAvoid(event) {
  let hasFinished = false;
  allDisabled.value = true;
  avoidObstacleSwitch.value = true
  try {
    const unwatch = watch(messages, (newValue) => {
      if (newValue.data.night_lights_state.result == 0 && !hasFinished) {
        hasFinished = true;
        allDisabled.value = false;
        avoidObstacleSwitch.value = false;
        console.log('执行完毕了-------------------------')
        // 停止监听 messages.value 的变化
        unwatch();
      } else if (newValue.data.night_lights_state.result != 0) {
        //执行失败
        avoidObstacleSwitch.value = false;
        aircraftSwitch.avoidObstacle = false
        allDisabled.value = false;
      }
    })

    if (event) {
      await addExecuteInstruct(3, 'obstacle_avoidance', { obstacle_avoidance: { upside: 1 } })
    } else {
      await addExecuteInstruct(3, 'obstacle_avoidance', { obstacle_avoidance: { upside: 0 } })
    }
  } catch {
    avoidObstacleSwitch.value = false;
    aircraftSwitch.avoidObstacle = false
    allDisabled.value = false;
  }
}

let heightLimitChangeTimer: ReturnType<typeof setTimeout>;
//限高
function heightLimitChange(event) {
  let hasFinished = false;
  try {
    if (heightLimitChangeTimer) {
      clearTimeout(heightLimitChangeTimer);
    }
    heightLimitChangeTimer = setTimeout(() => {
      console.log(event)
      allDisabled.value = true;
      const unwatch = watch(messages, (newValue) => {
        if (newValue.data.height_limit.result == 0 && !hasFinished) {
          hasFinished = true;
          allDisabled.value = false;
          console.log('执行完毕了-------------------------')
          // 停止监听 messages.value 的变化
          unwatch();
        }
      })

      addExecuteInstruct(3, 'height_limit', { height_limit: event })
    }, 1000);
  } catch {
    allDisabled.value = false;
  }
}
let distanceLimitChangeTimer: ReturnType<typeof setTimeout>;
//限远
function distanceLimitChange(event) {
  console.log(event)
  let hasFinished = false;
  try {
    if (distanceLimitChangeTimer) {
      clearTimeout(distanceLimitChangeTimer);
    }
    distanceLimitChangeTimer = setTimeout(() => {
      allDisabled.value = true;
      const unwatch = watch(messages, (newValue) => {
        if (newValue.data.distance_limit_status.distance_limit.result == 0 && !hasFinished) {
          hasFinished = true;
          allDisabled.value = false;
          console.log('执行完毕了-------------------------')
          // 停止监听 messages.value 的变化
          unwatch();
        }
      })

      addExecuteInstruct(3, 'height_limit', { distance_limit_status: { "distance_limit": event } })
    }, 1000)
  } catch {
    allDisabled.value = false;
  }
}

let safeLandHeightChangeTimer: ReturnType<typeof setTimeout>;
//备降转移高
function safeLandHeightChange(event) {
  let hasFinished = false;
  try {
    if (safeLandHeightChangeTimer) {
      clearTimeout(safeLandHeightChangeTimer);
    }
    safeLandHeightChangeTimer = setTimeout(() => {
      console.log(event)

      allDisabled.value = true;
      const unwatch = watch(messages, (newValue) => {
        if (newValue.data.rth_altitude.result == 0 && !hasFinished) {
          hasFinished = true;
          allDisabled.value = false;
          console.log('执行完毕了-------------------------')
          // 停止监听 messages.value 的变化
          unwatch();
        }
      })

      addExecuteInstruct(3, 'rth_altitude', { rth_altitude: event })
    }, 1000);
  } catch {
    allDisabled.value = false;
  }
}

//运行模式
function batteryStoreModeChange(event) {
  console.log(event)
  let hasFinished = false;
  allDisabled.value = true;
  try {

    const unwatch = watch(messages, (newValue) => {
      if (newValue.data.output.status == "ok" && !hasFinished) {
        hasFinished = true;
        allDisabled.value = false;
        console.log('执行完毕了-------------------------')
        // 停止监听 messages.value 的变化
        unwatch();
      }
    })

    addExecuteInstruct(3, 'battery_store_mode_switch', { action: event })
  } catch {
    allDisabled.value = false;
  }
}

// 在组件卸载前移除WebSocket监听器
onBeforeUnmount(() => {
  // removeWebSocketListener()
  offWebSocket(addWebSocketListener)
});

onMounted(() => {
  addWebSocketListener()
})
</script>
<style scoped lang="less">
/deep/ .scroll-container {
  padding: 0 !important;
}

.greyOut {
  filter: grayscale(100%);
}

.equipDebugBox {
  display: flex;
  align-items: center;

  .title {
    margin-right: 10px;
  }

  /deep/ .ant-switch-checked {
    background-color: #23a35c;
  }
}

.equipModalBox {
  padding: 20px;

  .headBox {
    .headTitleBox {
      display: flex;

      // border-bottom: 1px solid #ECECEC;
      // padding-bottom: 4px;

      .title1 {
        font-weight: 700;
        position: relative;
        padding-right: 10px;

        display: flex;
        align-items: center;

        .borBot {
          border-bottom: 2px solid #167DB5;
        }

        .TabsBox {
          display: flex;
          justify-content: center;
          width: 84px;
          height: 36px;
          cursor: pointer;

          .img {
            width: 20px;
            height: 20px;
            margin-right: 8px;
          }

          .text {
            font-weight: 700;
            color: #999999;
            font-size: 16px;
          }

          .text1 {
            font-weight: 700;
            color: #167DB5;
            font-size: 16px;
          }
        }
      }

      .title1::after {
        content: "";
        position: absolute;
        top: 0;
        right: 0;
        width: 1px;
        height: 66%;
        background-color: #dadbdd;
      }

      .title2 {
        padding: 0 10px;
        position: relative;
      }

      .title2::after {
        content: "";
        position: absolute;
        top: 0;
        right: 0;
        width: 1px;
        height: 66%;
        background-color: #dadbdd;
      }

      .title3 {
        .textBox {
          color: #1D986C;
          background-color: #F2F9F7;
          ;
          margin-left: 10px;
          // padding-left: 5px;
          padding: 2px 4px;
        }
      }

      .refreshData {
        padding-top: 7px;
        display: flex;
        flex: 1;
        justify-content: flex-end;
        cursor: pointer;
      }
    }
  }

  .airportBox {
    .equipInformBox {
      background: linear-gradient(to right, #090a0c, #586a7e);
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      margin-top: 15px;

      .left {
        display: flex;

        .img {
          width: 100px;
          height: 100px;
          border-radius: 10px;
          // background-color: #696a6e;
          margin-right: 15px;
          display: flex;
          align-items: center;
          justify-content: center;
          overflow: hidden;
        }

        .title {
          font-size: 20px;

          .title1 {
            font-weight: 1000;
            color: white;

          }

          .title2 {
            color: #acbdcf;
          }
        }
      }

      .right {
        color: #acbdcf;
        display: flex;

        // align-items: center;
        /deep/ .ant-typography {
          color: #acbdcf;
        }

      }
    }

    .deviceDetailBox {
      // padding: 20px 0;
      padding-top: 16px;

      .Box {
        text-align: center;
        background-color: #F8FBFD;
        padding: 15px 0;
        margin-bottom: 13px;

        .title {
          color: #636b6e;
          // font-size: 20px;
          font-size: 14px;
          font-weight: 400;
          color: #666666;
        }

        .text {
          color: #333333;
          font-weight: 500;
          font-size: 20px;
        }
      }

    }

    .controlBox {
      .title {
        font-size: 20px;
        font-weight: 1000;
      }

      .gray-div {
        filter: grayscale(100%);
      }

      .Box {
        display: flex;
        margin-bottom: 15px;

        .left {
          background-color: #edf7ff;
          width: 65px;
          height: auto;

          img {
            width: 100%;
            // height: 100%;
          }
        }

        .right {
          background-color: #f5fafe;
          flex: 1;
          padding: 8px;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .titleBox {
            .title {
              color: #616b74;
            }

            .text {
              color: #1d282e;
            }
          }

          .but {
            color: #9cc7f2;
            // font-size: 20px;
            font-weight: 700;
            background-color: #e8f2fe;
            // padding: 0 15px;
            border: none;
          }
        }
      }
    }
  }

  .droneBox {
    .equipInformBox {
      background: linear-gradient(316deg, #1F6196 0%, #084364 100%);
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 20px;
      margin-top: 15px;

      .left {
        display: flex;

        .img {
          width: 100px;
          height: 100px;
          border-radius: 10px;
          // background-color: #696a6e;
          margin-right: 15px;

          display: flex;
          align-items: center;
          justify-content: center;
          overflow: hidden;
        }

        .title {
          font-size: 20px;

          .title1 {
            font-weight: 1000;
            color: white;
          }

          .title2 {
            color: #acbdcf;

            .textBox {
              display: flex;
              align-items: center;

              .title {
                font-weight: 400;
                font-size: 14px;
                color: #CCCCCC;
              }

              .text {
                font-size: 14px;

                /deep/.ant-typography {
                  color: #CCCCCC;
                  margin-bottom: 0px !important;
                }
              }
            }
          }
        }
      }

      .right {
        display: flex;
        align-items: center;

        .title {
          color: #acbdcf;
          display: flex;
          align-items: center;
        }

        .text {
          font-size: 14px;


          /deep/.ant-typography {
            color: #acbdcf;
            margin-bottom: 0px !important;
          }
        }
      }
    }

    .deviceDetailBox {
      // padding: 20px 0;
      padding-top: 16px;

      .Box {
        text-align: center;
        background-color: #F8FBFD;
        padding: 15px 0;
        margin-bottom: 13px;

        .title {
          color: #636b6e;
          // font-size: 20px;
          font-size: 14px;
          font-weight: 400;
          color: #666666;
        }

        .text {
          color: #333333;
          font-weight: 500;
          font-size: 20px;
        }
      }

    }

    .batteryInformBox {
      margin-bottom: 8px;

      .left {
        background-color: #f8fbfd;
        // display: inline-block;
        // min-width: 449px;

        .leftHeadBox {
          border-bottom: 1px solid #f2f3f4;
          padding: 8px 14px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .text {
            font-size: 14px;
            color: #666666;
          }

          .battery {
            display: flex;
            align-items: center;

            .electroQuantity {
              color: #0CB883;
              margin-right: 5px;
            }
          }
        }

        .batteryBox {
          display: flex;
          align-items: center;
          justify-content: space-around;
          padding: 13px 0;

          .left {
            width: 100%;

            .topBox {
              text-align: center;
              margin-bottom: 12px;

              .title {
                color: #666666;
                font-size: 14px;
              }

              .val {
                font-size: 20px;
                color: #333333;
                font-weight: 700;
              }
            }

            .BotBox {
              text-align: center;

              .title {
                color: #666666;
                font-size: 14px;
              }

              .val {
                font-size: 20px;
                color: #333333;
                font-weight: 700;
              }
            }
          }

        }
      }
    }

    .aircraftSetupBox {
      .aircraftSetup {
        display: flex;
        justify-content: space-between;
        padding: 15px 12px;
        background-color: #F8FBFD;
        margin-bottom: 8px;

        .title {
          font-size: 14px;
          color: #666666;
          margin-right: 6px;

          display: flex;
          align-items: center;

          .text {
            margin-right: 6px;
          }
        }

        .switchBox {
          display: flex;
          align-items: center;


          .title {
            font-size: 14px;
            color: #666666;
          }

          /deep/ .ant-switch-checked {
            background-color: #23a35c;
          }

          .inp {
            width: 293px;
            background-color: #edf5fa;
          }

          /deep/ .ant-select-selector {
            background-color: #edf5fa;
          }
        }
      }
    }

    .controlBox {
      .title {
        font-size: 20px;
        font-weight: 1000;
      }

      .gray-div {
        filter: grayscale(100%);
      }

      .Box {
        display: flex;
        margin-bottom: 15px;

        .left {
          background-color: #edf7ff;
          width: 65px;
          height: auto;

          img {
            width: 100%;
          }
        }

        .right {
          background-color: #f5fafe;
          flex: 1;
          padding: 8px;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .titleBox {
            .title {
              color: #616b74;
            }

            .text {
              color: #1d282e;
            }
          }

          .but {
            color: #9cc7f2;
            // font-size: 20px;
            font-weight: 700;
            background-color: #e8f2fe;
            // padding: 0 15px;
            border: none;
          }
        }
      }
    }
  }
}
</style>
